/**
 * 类式组件
 */
import React from 'react';
import {Layout, Form, Input, Button, Table, ConfigProvider, message, Modal} from 'antd';
import '../assets/css/home.css'
import zhCN from 'antd/es/locale/zh_CN';
import AddStudentClass from "../components/AddStudentClass";
import UpdateStudentClass from "../components/UpdateStudentClass";
import axios from "axios";
import servicePath from "../config/apiConfig";
const { Header, Content } = Layout

let studentList = []
for(let i=11; i<=30; i++) {
    studentList.push({
        snumber: '2010500'+i,
        name: '小红',
        classes: '计算机2班',
        sex: '女',
        cscore: 95,
        jscore: 87,
        dbscore: 88
    })
}

class HomeClass extends React.PureComponent {
    state = {
        snumber: '',
        name: '',
        studentList: [],
        pagination: {
            currentPage: 1,
            pageSize: 2,
            total: 0,
        },
        loading: false,
        showAdd: false,
        showUpdate: false,
        studentInfo: {},
        isSearch: false
    }

    // 初始化表格列
    initColumns = ()=>{
        this.columns = [
            {
                title: '学号',
                dataIndex: 'snumber',
            },
            {
                title: '姓名',
                dataIndex: 'name',
            },
            {
                title: '班级',
                dataIndex: 'classes',
            },
            {
                title: '性别',
                dataIndex: 'sex',
            },
            {
                title: 'c语言成绩',
                dataIndex: 'cscore',
            },
            {
                title: 'java语言成绩',
                dataIndex: 'jscore',
            },
            {
                title: '数据库语言成绩',
                dataIndex: 'dbscore',
            },
            {
                title: '操作',
                render: (student) => (
                    <>
                        <Button type="primary" size="middle" className="table-btn table-update-btn" onClick={()=>this.updateStudent(student)}>修改</Button>
                        <Button type="danger" size="middle" className="table-btn" onClick={()=>this.deleteStudent(student)}>删除</Button>
                    </>
                ),
            }
        ];
    }


    // 搜索
    getSearchListByName = (name, currentPage, pageSize)=>{
        axios.get(servicePath.findByName,{ params: {name, currentPage, pageSize} }).then(res=>{
            let data = res.data
            if(data.code === 200) {
                this.setState({
                    studentList: data.msg.data,
                    pagination: {
                        currentPage: currentPage,
                        pageSize: pageSize,
                        total: data.msg.total
                    }
                })
            }
        })
    }
    getSearchListBySnumber = (snumber, currentPage, pageSize)=>{
        axios.get(servicePath.findBySnumber+snumber).then(res=>{
            let data = res.data
            if(data.code === 200) {
                this.setState({
                    studentList: data.msg.data,
                    pagination: {
                        currentPage: currentPage,
                        pageSize: pageSize,
                        total: data.msg.total
                    }
                })
            }
        })
    }
    search = ()=>{
        const {snumber, name, pagination} = this.state
        this.setState({
            isSearch: true
        })
        if(snumber.trim()) {
            this.getSearchListBySnumber(snumber.trim(), 1, pagination.pageSize);
        } else if(name.trim()) {
            this.getSearchListByName(name.trim(), 1, pagination.pageSize)
        }
    }
    // 重置
    resetForm =()=>{
        this.setState({
            isSearch: false,
            snumber: '',
            name: ''
        })
        this.getStudentList(1, this.state.pagination.pageSize);
    }
    // 录入学生信息
    addStudent =()=>{
        this.setState({
            showAdd: true
        })
    }
    // 更新学生信息
    updateStudent = (student)=>{
        this.setState({
            showUpdate: true,
            studentInfo: student
        })
    }
    // 删除学生信息
    deleteStudent = (student)=>{
        const { pagination } = this.state
        const that = this
        Modal.confirm({
            title: '确定要删除此条记录吗?',
            content: '如果你点击确定按钮，该记录将会永远被删除，无法恢复',
            onOk() {
                axios.delete(servicePath.deleteStudent + student.id).then(res=>{
                    const data = res.data
                    if(data.code===200) {
                        message.success('删除学生信息成功！',1);
                        if((pagination.currentPage-1)*pagination.pageSize===pagination.total-1) {
                            let current = pagination.currentPage>1 ? pagination.currentPage-1 : 1
                            that.getStudentList(current, pagination.pageSize)
                        } else {
                            that.getStudentList(pagination.currentPage, pagination.pageSize)
                        }
                    } else {
                        message.error('删除学生信息失败！',1);
                    }
                })
            },
            onCancel() {
                message.info('取消删除！',1);
            },
        });
    }
    // 导出成绩
    download =()=>{
        console.log('导出学生成绩')
        axios.get(servicePath.exportToExcel, { responseType: 'blob' }).then(res => {
            console.log(res)
            // const blob = new Blob([res.data], {
            //   type: 'application/octet-stream;charset=utf-8'
            // })
            const blob = new Blob([res.data], {
                type: 'application/vnd.ms-excel;charset=utf-8'
            })
            const url = window.URL.createObjectURL(blob)
            const link = document.createElement('a')
            link.href = url
            link.download = `学生成绩单_${decodeURI(
                res.headers['content-disposition'].split('_')[1]
            )}`
            // console.log(res.headers['content-disposition'])
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
        }).catch(function (error) {
            console.log(error)
        })
    }

    // 关闭添加对话框
    closeAddModal = ()=>{
        if(this.state.isSearch) {
            this.resetForm();
        } else {
            this.getStudentList(1, this.state.pagination.pageSize);
        }
        this.setState({
            showAdd: false
        })
    }
    // 关闭更新对话框
    closeUpdateModal = ()=>{
        const {isSearch, name, snumber, pagination} = this.state
        this.setState({
            showUpdate: false,
            studentInfo: {}
        })
        if(isSearch) {
            if(name.trim()) {
                this.getSearchListByName(name.trim(), pagination.currentPage, pagination.pageSize)
            } else {
                this.getSearchListBySnumber(snumber.trim(), pagination.currentPage, pagination.pageSize);
            }
        } else {
            this.getStudentList(pagination.currentPage, pagination.pageSize)
        }
    }

    // 改变当前页码或每页多少条
    changePage = (currentPage, pageSize)=>{
        if(this.state.isSearch) {
            if(this.state.name.trim()) {
                this.getSearchListByName(this.state.name.trim(), currentPage, pageSize)
            } else {
                this.getSearchListBySnumber(this.state.snumber.trim(), currentPage, pageSize);
            }
        } else {
            this.getStudentList(currentPage, pageSize)
        }
    }

    // 获取学生信息列表
    getStudentList = (currentPage, pageSize)=>{
        axios.get(servicePath.getStudentList,{params: {currentPage, pageSize}}).then(res=>{
            let data = res.data
            if(data.code === 200) {
                this.setState({
                    studentList: data.msg.data,
                    pagination: {
                        currentPage: currentPage,
                        pageSize: pageSize,
                        total: data.msg.total
                    }
                })
            }
        })
    }

    componentDidMount() {
        this.initColumns()
        /*this.setState({
            studentList: studentList
        })*/
        this.getStudentList(1, this.state.pagination.pageSize)
    }


    render() {
        const { snumber, name, studentList, pagination, loading, showAdd, showUpdate, studentInfo } = this.state
        const paginationProps = {
            position: 'bottom-center',
            showSizeChanger: true, //设置每页显示数据条数
            showQuickJumper: true,
            showTotal: () => `共${pagination.total}条`,
            current: pagination.currentPage,
            pageSize: pagination.pageSize,
            total: pagination.total,  //数据的总的条数
            onChange: (current, pageSize) => this.changePage(current, pageSize), //点击当前页码
            onShowSizeChange: (current, pageSize) => { //设置每页显示数据条数，current表示当前页码，pageSize表示每页展示数据条数
                this.changePage(current, pageSize)
            }
        }

        return (
            <div className="home-container">
                <Layout className="layout">
                    <Header className="layout-header">
                        简易学生成绩管理系统
                    </Header>

                    <Form name="horizontal_search" layout="inline" className="layout-search">
                        <Form.Item label="学号">
                            <Input placeholder="精确匹配" value={snumber} size="small" onChange={(e)=>{this.setState({snumber:e.target.value})}}/>
                        </Form.Item>
                        <Form.Item label="姓名">
                            <Input placeholder="模糊匹配" value={name} size="small" onChange={(e)=>{this.setState({name:e.target.value})}}/>
                        </Form.Item>
                        <Form.Item>
                            <Button type="primary" size="small" className="form-btn" onClick={this.search}>查询</Button>
                            <Button type="default" size="small" className="form-btn reset-btn" onClick={this.resetForm}>重置</Button>
                            <Button type="default" size="small" className="form-btn add-btn" onClick={this.addStudent}>录入</Button>
                            <Button type="dashed" size="small" className="form-btn" onClick={this.download}>导出成绩</Button>
                        </Form.Item>
                    </Form>

                    <Content className="layout-Content">
                        <ConfigProvider locale={zhCN}>
                            <Table bordered columns={this.columns} dataSource={studentList} scroll={{ y: 400 }}
                                   rowKey={record => record.snumber} loading={loading} pagination={paginationProps} />
                        </ConfigProvider>

                    </Content>
                </Layout>

                {
                    showAdd ? (<AddStudentClass isVisible={showAdd} closeModal={this.closeAddModal}/>) : null
                }
                {
                    showUpdate ? (<UpdateStudentClass isVisible={showUpdate} closeModal={this.closeUpdateModal} studentInfo={studentInfo}/>) : null
                }
            </div>
        )
    }
}



export default HomeClass



